package com.wowjoy.dp.sds.aop;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class ExecuteTimeAspects {

    @Pointcut(value = "within(com.wowjoy.dp.sds.service..*)")
    public void executeTimePoint() {}

    @Around(value = "executeTimePoint()")
    public Object timeAround(ProceedingJoinPoint joinPoint) {
        StopWatch clock = new StopWatch();
        clock.start();
        Object result = null;
        try {
            result = joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("[耗时拦截器]-方法执行出错:{}", throwable.getMessage());
            throwable.printStackTrace();
        }
        clock.stop();
        long time = clock.getTime();
        if (time >= 1000) {
            log.warn("[耗时拦截器]-{}", clock.getTime() + " ms"
                    + "." + joinPoint.getSignature().getDeclaringTypeName()
                    + "." + joinPoint.getSignature().getName()
                    + "(" + StringUtils.join(joinPoint.getArgs(), ",") + ")" +
                    "]");
        }
        return result;
    }
}
